import { Component, Host, ChangeDetectionStrategy, ChangeDetectorRef, ViewChild } from '@angular/core';
import { AppComponent } from '../../../../app.component';
import { CompanyService } from '../company.service';
import { CompanySustainableProductsService } from './companySustainableProducts.service';
import { InvolvementAssessmentModel } from '../productInvolvement/models/involvementAssessment.model';
import { CompanySustainableProductsModel } from "./models/companySustainableProducts.model";
import { CompanyReportDownloadModel } from '../shared/companyHeader/companyReportDownload/companyReportDownload.model';
import { CompanyModel } from '../company.model';
import { UtilsService } from '../../../../shared/services/utils.service';
import { ModalComponent } from '../../../../shared/components/modal/modal.component';
import { AnalyticsService } from '../../../../shared/services/googleAnalytics.service';
import { GoogleAnalyticsBeacon, ReportAnalytics } from '../../../../shared/models/googleAnalytics.model';
import { BaseComponent } from '../../../../shared/components/baseComponent/base.component';
import { SustainableProductsCategory, SustainableProductsUtils } from '../../sustainableProducts/sustainableProductsUtils/sustainableProductsUtils';

/**
 * Company product involvement main component
 *
 * Author: Sorin Spiru
 * Date: 13.01.2018
 */
@Component({
    moduleId: module.id,
    templateUrl: 'companySustainableProducts.component.html',
    styleUrls: ['./companySustainableProducts.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    providers: [CompanySustainableProductsService]
})
export class CompanySustainableProductsComponent extends BaseComponent {
    public assessments: InvolvementAssessmentModel[];
    public companyInvolvement: CompanySustainableProductsModel;
    public selectedAssessment = undefined;
    public errorMessage = undefined;
    public company: CompanyModel;
    public downloadData: CompanyReportDownloadModel;
    public analyticsData: ReportAnalytics = new ReportAnalytics('Research', 'PDFComplianceReport');
    public hasActiveInvolvedAssessments: boolean;
    public categories: SustainableProductsCategory[] = [];
    public sustainableProductsUtils: SustainableProductsUtils = new SustainableProductsUtils();
    public indicatorCategories:any[] = [];

    @ViewChild('sustainableProductsModal') sustainableProductsModal: ModalComponent;

    constructor(
        private cdRef: ChangeDetectorRef,
        public companyService: CompanyService,
        private companySustainableProductsService: CompanySustainableProductsService,
        @Host() private rootComponent: AppComponent,
        private analyticsService: AnalyticsService
    ) {
        super(cdRef);
    }

    ngOnInit() {
        this.categories = this.sustainableProductsUtils.getSustainableProductsCategories();
        this.companySustainableProductsService.getAssessments().subscribe(data => {
            this.assessments = data;
            
            this.indicatorCategories = this.assessments.map( x => x.categories);
                
            this.companyService.company.subscribe(company => {
                this.company = company;

                //this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon('OnscreenComplianceReport', 'Research', { CompanyId: this.company.id }));

                this.companyService.setHeaderData(undefined);

                this.companySustainableProductsService.getCompanyInvolvementAssessment(company.id)
                    .subscribe(data => {
                        if (data.status === 200) {
                            this.companyInvolvement = data.body;
                            this.hasActiveInvolvedAssessments = this.assessments.some(x => this.isInvolved(x) && x.hasAccess);
                            this.cdRef.markForCheck();

                            // set download report data
                            //this.downloadData = this.companyService.getSustainableProductsDownloadData(this.company);
                        } else if (data.body.hasOwnProperty('message')) {
                            this.errorMessage = data.body.message;
                        }
                        this.cdRef.markForCheck();
                    });


                this.rootComponent.finishLoading();
            });
        });
    }

    public isInvolved(assessment: InvolvementAssessmentModel): boolean {
        var indicator = this.getInvolvementAssessment(assessment);
        return indicator !== undefined && !indicator.isNotResearched;
    }

    public isNotResearched(assessment: InvolvementAssessmentModel): boolean {
        var indicator = this.getInvolvementAssessment(assessment);
        if (indicator !== undefined)
            return indicator.isNotResearched;

        return false;
    }

    private getInvolvementAssessment(assessment: InvolvementAssessmentModel) {
        return this.companyInvolvement.indicators.find((indicator) => 
            assessment.symbol == indicator.symbol);
    }

    public setSelectedAssessment(assessment: InvolvementAssessmentModel): void {
        this.selectedAssessment = this.getInvolvementAssessment(assessment);
    }

    public getAssessmentIcon(assessment: InvolvementAssessmentModel, on:string="off"): string {
        let iconName = 'icn-sp-' + assessment.symbol + '-';

        if ((this.isInvolved(assessment) && assessment.hasAccess) || on =="on" ) {
            iconName = iconName + 'on';
        } else {
            iconName = iconName + 'off';
        }

        return UtilsService.getIconFilename(iconName, 'SustainableProducts', 'svg', true);
    }

    public getAssessmentDescription(assessment: InvolvementAssessmentModel): string {
        return this.categories.find(x => x.symbol == assessment.symbol).description;
    }

    public showDetails(assessment: InvolvementAssessmentModel) {
        if (this.isInvolved(assessment) && assessment.hasAccess)
            this.sustainableProductsModal.show();
    }

    public getCategoriesForAssessment(assessment: InvolvementAssessmentModel) {
       return this.indicatorCategories.find( x => x.find( y => y.symbol.includes(assessment.symbol)));
    }
}
